﻿using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    public class OrgUnitEntityConfig : IEntityTypeConfiguration<OrgUnit>
    {
        public void Configure(EntityTypeBuilder<OrgUnit> builder)
        {
            builder.ToTable("T_OrgUnits");
            builder.HasOne<OrgUnit>(u => u.Parent) // 根节点无parent，可为空
                .WithMany(u => u.Children)
                // 对应Parent属性设为可空类型，即加问号；或者 使用显式外键属性
                //.HasForeignKey(u => u.ParentId)
                .OnDelete(DeleteBehavior.NoAction) // 解决下面错误,外键，级联关系，删除无动作
                //.IsRequired() 
                ;
            //Failed executing DbCommand(22ms)[Parameters = [], CommandType = 'Text', CommandTimeout = '30']
            //CREATE TABLE[T_OrgUnits] (
            //    [Id] bigint NOT NULL IDENTITY,
            //    [Name] nvarchar(100) NOT NULL,
            //    [ParentId] bigint NOT NULL,
            //    CONSTRAINT[PK_T_OrgUnits] PRIMARY KEY([Id]),
            //    CONSTRAINT[FK_T_OrgUnits_T_OrgUnits_ParentId] FOREIGN KEY([ParentId]) REFERENCES[T_OrgUnits]([Id]) ON DELETE CASCADE
            //);
            //Microsoft.Data.SqlClient.SqlException(0x80131904): Introducing FOREIGN KEY constraint 'FK_T_OrgUnits_T_OrgUnits_ParentId'
            //on table 'T_OrgUnits' may cause cycles or multiple cascade paths.Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or
            //modify other FOREIGN KEY constraints.
            //Could not create constraint or index.See previous errors.

            builder.Property(o => o.Name).IsRequired()
                .IsUnicode().HasMaxLength(100);
        }
    }
}
